from django.contrib.auth.backends import ModelBackend
from .models import User
import re

class MobileBackend(ModelBackend):
    """自定义手机号认证后端"""
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 判断用户名是否为手机号
        if re.match('^1[3-9]\d{9}$', username):
            # 手机号登录
            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist:
                return None
        else:
            # 用户名登录
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return None
        
        # 验证密码
        if user.check_password(password):
            return user
        return None